package com.zelin.servlet;

import cn.hutool.core.util.StrUtil;
import com.zelin.pojo.student;
import com.zelin.service.StudentService;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet{
    private  StudentService studentService;

    @Override
    public void init() throws ServletException {
        studentService = WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getBean(StudentService.class);
    }

    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String cmd = req.getParameter("cmd");
        if (StrUtil.isNotBlank(cmd)){
            if ("list".equals(cmd)){
                list(req,resp);
            }
        }
    }

    private void list(ServletRequest req, ServletResponse resp) throws IOException {
        List<student>students=studentService.findAll();
        resp.getWriter().println(students);
        resp.getWriter().flush();
        System.out.println("students = " + students);


    }
}
